package com.leyou.user.controller;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import com.leyou.user.pojo.Image;
import com.leyou.user.pojo.Info;
import com.leyou.user.service.InfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("info")
public class InfoController {

    @Autowired
    private InfoService infoService;

    @Autowired
    private JwtProperties prop;

    @PostMapping("add")
    public ResponseEntity<Void> addInfo(@CookieValue(value = "LY_TOKEN", defaultValue = "") String token,@RequestBody Info info){

        try {
            UserInfo user = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            info.setUserId(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        this.infoService.addInfo(info);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("find")
    public ResponseEntity<Info> findInfo(@CookieValue(value = "LY_TOKEN", defaultValue = "") String token){
        try {
            UserInfo user = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            Info info = this.infoService.findInfo(user.getId());
            if(info == null){
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            return ResponseEntity.ok(info);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
    }

    @PostMapping("addimage")
    public ResponseEntity<Void> addImage(@CookieValue(value = "LY_TOKEN", defaultValue = "") String token,@RequestBody Info info){
        try {
            UserInfo user = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            info.setUserId(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        this.infoService.addImage(info);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PutMapping("deleteimage")
    public ResponseEntity<Void> deleteImage(@RequestBody Image image){
        this.infoService.deleteImage(image);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
